const router = require('koa-router')()
const mongoose = require('mongoose')
const crypto = require('crypto')
const statsfn = require('../lib/statsfn')
const Comment = mongoose.model('Comment')
const User = mongoose.model('User')
const Image = mongoose.model('Image')

router.get('/', async (ctx, next) => {
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const comments = await Comment.find({})
    .sort({createdAt: -1}).limit(3)
  const stats = await statsfn()
  await ctx.render('index', {
    title: '图片分享',
    images,
    stats,
    username:ctx.session.username,
    nickname:ctx.session.nickname,
    comments
  })
})

router.get('/login',async ctx => {
  await ctx.render('login',{})
})

router.get('/register',async ctx => {
  await ctx.render('register',{})
})

router.post('/login',async ctx => {
  const {username,password} = ctx.request.body
  const psd = await User.findOne({username: username})
  const md5 = crypto.createHash('md5')
  md5.update(password)
  // console.log(md5.digest('hex'))
  if(md5.digest('hex') === psd.password){
    ctx.session.nickname = psd.nickname
    ctx.redirect('/')
  }else{
    ctx.redirect('/login')
  }
})

router.get('/logout',async ctx => {
  ctx.session.nickname = undefined
  ctx.redirect('/')
})

router.post('/register',async ctx => {
  ctx.redirect('/login')
})

module.exports = router
